/**
 * 商家端微信小程序 - "我的"页面相关API接口
 * 基于现有后端接口风格设计
 */

import request from './api';

/**
 * ==================== 个人中心相关接口 ====================
 */
export const ProfileAPI = {
  
  /**
   * 获取商家个人信息
   * GET /merchant/info
   */
  getMerchantProfile: () => {
    return request({
      url: '/merchant/info',
      method: 'GET'
    })
  },

  /**
   * 更新商家个人信息
   * PUT /merchant/profile/update
   */
  updateMerchantProfile: (params: {
    merchantName?: string;        // 商家名称
    contactPerson?: string;       // 联系人姓名
    contactPhone?: string;        // 联系电话
    avatarUrl?: string;          // 头像URL
    address?: string;            // 地址
    latitude?: number;           // 纬度
    longitude?: number;          // 经度
    description?: string;        // 商家描述
    businessHours?: {            // 营业时间
      start: string;
      end: string;
    };
    businessStatus?: number;     // 营业状态 1-营业中 0-休息中
  }) => {
    return request({
      url: '/merchant/profile/update',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 上传商家头像
   * POST /merchant/profile/upload-avatar
   */
  uploadAvatar: (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')
      
      wx.uploadFile({
        url: '/merchant/profile/upload-avatar',
        filePath: filePath,
        name: 'avatar',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              resolve(data)
            } else {
              reject(data)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  },

  /**
   * 获取商家认证状态
   * GET /merchant/profile/verify-status
   */
  getVerifyStatus: () => {
    return request({
      url: '/merchant/profile/verify-status',
      method: 'GET'
    })
  },

  /**
   * 获取商家统计概览
   * GET /merchant/profile/statistics
   */
  getProfileStatistics: () => {
    return request({
      url: '/merchant/profile/statistics',
      method: 'GET'
    })
  },

  /**
   * 更新商家地址信息（专门的地址更新接口）
   * PUT /merchant/profile/update-address
   */
  updateMerchantAddress: (params: {
    address: string;              // 详细地址
    latitude: number;             // 纬度
    longitude: number;            // 经度
    locationName?: string;        // 位置名称
    province?: string;            // 省份
    city?: string;               // 城市
    district?: string;           // 区县
    street?: string;             // 街道
    streetNumber?: string;       // 门牌号
  }) => {
    return request({
      url: '/merchant/profile/update-address',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 验证商家地址是否在服务范围内
   * POST /merchant/profile/validate-address
   */
  validateAddress: (params: {
    latitude: number;
    longitude: number;
    address: string;
  }) => {
    return request({
      url: '/merchant/profile/validate-address',
      method: 'POST',
      data: params
    })
  },

  /**
   * 获取地址建议（基于当前位置）
   * GET /merchant/profile/address-suggestions
   */
  getAddressSuggestions: (params: {
    latitude: number;
    longitude: number;
    keyword?: string;
  }) => {
    return request({
      url: '/merchant/profile/address-suggestions',
      method: 'GET',
      data: params
    })
  }
}

/**
 * ==================== 钱包相关接口 ====================
 */
export const WalletAPI = {
  
  /**
   * 获取钱包概览信息
   * GET /merchant/wallet/overview
   */
  getWalletOverview: () => {
    return request({
      url: '/merchant/wallet/overview',
      method: 'GET'
    })
  },

  /**
   * 获取钱包详细信息
   * GET /merchant/wallet/info
   */
  getWalletInfo: () => {
    return request({
      url: '/merchant/wallet/info',
      method: 'GET'
    })
  },

  /**
   * 获取钱包余额
   * GET /merchant/wallet/balance
   */
  getWalletBalance: () => {
    return request({
      url: '/merchant/wallet/balance',
      method: 'GET'
    })
  },

  /**
   * 获取收支明细列表
   * GET /merchant/wallet/transactions
   */
  getTransactionList: (params: {
    pageNum?: number;            // 页码，默认1
    pageSize?: number;           // 每页数量，默认20
    transactionType?: number;    // 交易类型 1-收入 2-支出 0-全部
    businessType?: number;       // 业务类型 1-订单收入 2-提现 3-退款 4-佣金
    startDate?: string;          // 开始日期 YYYY-MM-DD
    endDate?: string;            // 结束日期 YYYY-MM-DD
    keyword?: string;            // 搜索关键词
  }) => {
    return request({
      url: '/merchant/wallet/transactions',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取交易详情
   * GET /merchant/wallet/transactions/{transactionId}
   */
  getTransactionDetail: (transactionId: string) => {
    return request({
      url: `/merchant/wallet/transactions/${transactionId}`,
      method: 'GET'
    })
  },

  /**
   * 申请提现
   * POST /merchant/wallet/withdraw/apply
   */
  applyWithdraw: (params: {
    amount: number;              // 提现金额
    bankCardId: string;          // 银行卡ID
    remark?: string;             // 备注
    withdrawType?: number;       // 提现类型 1-普通提现 2-快速提现
  }) => {
    return request({
      url: '/merchant/wallet/withdraw/apply',
      method: 'POST',
      data: params
    })
  },

  /**
   * 获取提现记录
   * GET /merchant/wallet/withdraw/records
   */
  getWithdrawRecords: (params: {
    pageNum?: number;
    pageSize?: number;
    status?: number;             // 提现状态 0-待审核 1-处理中 2-已完成 3-已拒绝
    startDate?: string;
    endDate?: string;
  }) => {
    return request({
      url: '/merchant/wallet/withdraw/records',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取提现配置信息
   * GET /merchant/wallet/withdraw/config
   */
  getWithdrawConfig: () => {
    return request({
      url: '/merchant/wallet/withdraw/config',
      method: 'GET'
    })
  }
}

/**
 * ==================== 银行卡管理接口 ====================
 */
export const BankCardAPI = {
  
  /**
   * 获取银行卡列表
   * GET /merchant/bankcard/list
   */
  getBankCardList: () => {
    return request({
      url: '/merchant/bankcard/list',
      method: 'GET'
    })
  },

  /**
   * 获取银行卡详情
   * GET /merchant/bankcard/{cardId}
   */
  getBankCardDetail: (cardId: number | string) => {
    return request({
      url: `/merchant/bankcard/${cardId}`,
      method: 'GET'
    })
  },

  /**
   * 添加银行卡
   * POST /merchant/bankcard/add
   */
  addBankCard: (params: {
    bankName: string;            // 银行名称（必填）
    bankCode?: string;           // 银行编码
    branchName?: string;         // 开户支行名称
    cardNumber: string;          // 银行卡号（必填）
    cardHolderName: string;      // 持卡人姓名（必填）
    cardHolderIdcard: string;    // 持卡人身份证号（必填）
    cardHolderPhone: string;     // 持卡人预留手机号（必填）
    cardType: number;           // 卡类型：1-借记卡，2-贷记卡，3-对公账户（必填）
    setAsDefault?: boolean;     // 是否设为默认卡
  }) => {
    return request({
      url: '/merchant/bankcard/add',
      method: 'POST',
      data: params
    })
  },

  /**
   * 设置默认银行卡
   * PUT /merchant/bankcard/{cardId}/set-default
   */
  setDefaultBankCard: (cardId: number | string) => {
    return request({
      url: `/merchant/bankcard/${cardId}/set-default`,
      method: 'PUT'
    })
  },

  /**
   * 删除银行卡
   * DELETE /merchant/bankcard/{cardId}
   */
  deleteBankCard: (cardId: number | string) => {
    return request({
      url: `/merchant/bankcard/${cardId}`,
      method: 'DELETE'
    })
  },

  /**
   * 验证银行卡
   * POST /merchant/bankcard/{cardId}/verify
   */
  verifyBankCard: (cardId: number | string) => {
    return request({
      url: `/merchant/bankcard/${cardId}/verify`,
      method: 'POST'
    })
  },

  /**
   * OCR识别银行卡（如果后端支持）
   * POST /merchant/bankcard/ocr
   * @param imageUrl 银行卡图片URL（已上传到服务器的图片地址）
   * @returns 识别结果：{ cardNumber, bankName, bankCode }
   */
  recognizeBankCard: (imageUrl: string) => {
    return request({
      url: '/merchant/bankcard/ocr',
      method: 'POST',
      data: { imageUrl }
    })
  }
}

/**
 * ==================== 系统设置相关接口 ====================
 */
export const SettingsAPI = {
  
  /**
   * 获取消息通知设置
   * GET /merchant/settings/notifications
   */
  getNotificationSettings: () => {
    return request({
      url: '/merchant/settings/notifications',
      method: 'GET'
    })
  },

  /**
   * 更新消息通知设置
   * PUT /merchant/settings/notifications
   */
  updateNotificationSettings: (params: {
    orderNotification?: boolean;     // 订单通知
    messageNotification?: boolean;   // 消息通知
    systemNotification?: boolean;    // 系统通知
    soundEnabled?: boolean;          // 声音提醒
    vibrationEnabled?: boolean;      // 震动提醒
    quietHours?: {                   // 免打扰时间
      enabled: boolean;
      startTime: string;             // 开始时间 HH:mm
      endTime: string;               // 结束时间 HH:mm
    };
    notificationTypes?: {            // 具体通知类型设置
      newOrder?: boolean;            // 新订单
      orderCancelled?: boolean;      // 订单取消
      orderCompleted?: boolean;      // 订单完成
      customerMessage?: boolean;     // 客户消息
      systemAnnouncement?: boolean;  // 系统公告
      promotionReminder?: boolean;   // 促销提醒
    };
  }) => {
    return request({
      url: '/merchant/settings/notifications',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 获取打印机设置
   * GET /merchant/settings/printer
   */
  getPrinterSettings: () => {
    return request({
      url: '/merchant/settings/printer',
      method: 'GET'
    })
  },

  /**
   * 更新打印机设置
   * PUT /merchant/settings/printer
   */
  updatePrinterSettings: (params: {
    printerEnabled?: boolean;        // 是否启用打印
    printerType?: number;           // 打印机类型 1-热敏打印机 2-针式打印机
    printContent?: {                // 打印内容设置
      orderInfo?: boolean;          // 订单信息
      customerInfo?: boolean;       // 客户信息
      itemDetails?: boolean;        // 商品详情
      totalAmount?: boolean;        // 总金额
      qrCode?: boolean;            // 二维码
    };
    autoPrint?: boolean;            // 自动打印
    printCopies?: number;           // 打印份数
    paperSize?: string;             // 纸张规格
  }) => {
    return request({
      url: '/merchant/settings/printer',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 测试打印机连接
   * POST /merchant/settings/printer/test
   */
  testPrinter: () => {
    return request({
      url: '/merchant/settings/printer/test',
      method: 'POST'
    })
  },

  /**
   * 获取应用设置
   * GET /merchant/settings/app
   */
  getAppSettings: () => {
    return request({
      url: '/merchant/settings/app',
      method: 'GET'
    })
  },

  /**
   * 更新应用设置
   * PUT /merchant/settings/app
   */
  updateAppSettings: (params: {
    language?: string;              // 语言设置
    theme?: string;                 // 主题设置
    autoRefresh?: boolean;          // 自动刷新
    refreshInterval?: number;       // 刷新间隔（秒）
    dataUsageAlert?: boolean;       // 流量提醒
  }) => {
    return request({
      url: '/merchant/settings/app',
      method: 'PUT',
      data: params
    })
  }
}

/**
 * ==================== 帮助与支持相关接口 ====================
 */
export const SupportAPI = {
  
  /**
   * 获取常见问题列表
   * GET /merchant/support/faq
   */
  getFAQList: (params?: {
    category?: string;              // 问题分类
    keyword?: string;               // 搜索关键词
  }) => {
    return request({
      url: '/merchant/support/faq',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取FAQ详情
   * GET /merchant/support/faq/{faqId}
   */
  getFAQDetail: (faqId: string) => {
    return request({
      url: `/merchant/support/faq/${faqId}`,
      method: 'GET'
    })
  },

  /**
   * 获取协议文档列表
   * GET /merchant/support/agreements
   */
  getAgreementList: () => {
    return request({
      url: '/merchant/support/agreements',
      method: 'GET'
    })
  },

  /**
   * 获取协议详情
   * GET /merchant/support/agreements/{agreementId}
   */
  getAgreementDetail: (agreementId: string) => {
    return request({
      url: `/merchant/support/agreements/${agreementId}`,
      method: 'GET'
    })
  },

  /**
   * 获取隐私政策
   * GET /merchant/support/privacy-policy
   */
  getPrivacyPolicy: () => {
    return request({
      url: '/merchant/support/privacy-policy',
      method: 'GET'
    })
  },

  /**
   * 提交意见反馈
   * POST /merchant/support/feedback
   */
  submitFeedback: (params: {
    type: number;                   // 反馈类型 1-功能建议 2-问题反馈 3-其他
    title: string;                  // 反馈标题
    content: string;                // 反馈内容
    images?: string[];              // 图片附件
    contactInfo?: string;           // 联系方式
  }) => {
    return request({
      url: '/merchant/support/feedback',
      method: 'POST',
      data: params
    })
  },

  /**
   * 获取客服联系方式
   * GET /merchant/support/contact
   */
  getContactInfo: () => {
    return request({
      url: '/merchant/support/contact',
      method: 'GET'
    })
  },

  /**
   * 发起在线客服会话
   * POST /merchant/support/chat/start
   */
  startCustomerService: () => {
    return request({
      url: '/merchant/support/chat/start',
      method: 'POST'
    })
  }
}

/**
 * ==================== 缓存管理相关接口 ====================
 */
export const CacheAPI = {
  
  /**
   * 获取缓存信息
   * GET /merchant/cache/info
   */
  getCacheInfo: () => {
    return request({
      url: '/merchant/cache/info',
      method: 'GET'
    })
  },

  /**
   * 清理应用缓存
   * POST /merchant/cache/clear
   */
  clearCache: (params?: {
    cacheTypes?: string[];          // 缓存类型 ['images', 'data', 'logs']
  }) => {
    return request({
      url: '/merchant/cache/clear',
      method: 'POST',
      data: params
    })
  },

  /**
   * 获取存储使用情况
   * GET /merchant/cache/storage-usage
   */
  getStorageUsage: () => {
    return request({
      url: '/merchant/cache/storage-usage',
      method: 'GET'
    })
  }
}

/**
 * ==================== 账户安全相关接口 ====================
 */
export const SecurityAPI = {
  
  /**
   * 修改登录密码
   * PUT /merchant/security/change-password
   */
  changePassword: (params: {
    oldPassword: string;            // 原密码
    newPassword: string;            // 新密码
    confirmPassword: string;        // 确认新密码
  }) => {
    return request({
      url: '/merchant/security/change-password',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 绑定/更换手机号
   * PUT /merchant/security/bind-phone
   */
  bindPhone: (params: {
    newPhone: string;               // 新手机号
    smsCode: string;                // 短信验证码
    oldPhone?: string;              // 原手机号（更换时需要）
    oldSmsCode?: string;            // 原手机号验证码（更换时需要）
  }) => {
    return request({
      url: '/merchant/security/bind-phone',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 发送安全验证短信
   * POST /merchant/security/send-sms
   */
  sendSecuritySms: (params: {
    phone: string;                  // 手机号
    type: string;                   // 验证类型 'change_password' | 'bind_phone' | 'unbind_phone'
  }) => {
    return request({
      url: '/merchant/security/send-sms',
      method: 'POST',
      data: params
    })
  },

  /**
   * 获取登录记录
   * GET /merchant/security/login-records
   */
  getLoginRecords: (params?: {
    pageNum?: number;
    pageSize?: number;
    startDate?: string;
    endDate?: string;
  }) => {
    return request({
      url: '/merchant/security/login-records',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取账户安全等级
   * GET /merchant/security/level
   */
  getSecurityLevel: () => {
    return request({
      url: '/merchant/security/level',
      method: 'GET'
    })
  }
}

/**
 * ==================== 系统信息相关接口 ====================
 */
export const SystemAPI = {
  
  /**
   * 获取应用版本信息
   * GET /merchant/system/version
   */
  getVersionInfo: () => {
    return request({
      url: '/merchant/system/version',
      method: 'GET'
    })
  },

  /**
   * 检查更新
   * GET /merchant/system/check-update
   */
  checkUpdate: () => {
    return request({
      url: '/merchant/system/check-update',
      method: 'GET'
    })
  },

  /**
   * 获取系统公告
   * GET /merchant/system/announcements
   */
  getSystemAnnouncements: (params?: {
    pageNum?: number;
    pageSize?: number;
    type?: string;                  // 公告类型
  }) => {
    return request({
      url: '/merchant/system/announcements',
      method: 'GET',
      data: params
    })
  },

  /**
   * 标记公告已读
   * PUT /merchant/system/announcements/{announcementId}/read
   */
  markAnnouncementRead: (announcementId: string) => {
    return request({
      url: `/merchant/system/announcements/${announcementId}/read`,
      method: 'PUT'
    })
  },

  /**
   * 获取系统配置
   * GET /merchant/system/config
   */
  getSystemConfig: () => {
    return request({
      url: '/merchant/system/config',
      method: 'GET'
    })
  }
}

/**
 * ==================== 数据统计相关接口 ====================
 */
export const StatisticsAPI = {
  
  /**
   * 获取个人中心统计数据
   * GET /merchant/statistics/profile-summary
   */
  getProfileSummary: () => {
    return request({
      url: '/merchant/statistics/profile-summary',
      method: 'GET'
    })
  },

  /**
   * 获取本月收益统计
   * GET /merchant/statistics/monthly-revenue
   */
  getMonthlyRevenue: (params?: {
    year?: number;
    month?: number;
  }) => {
    return request({
      url: '/merchant/statistics/monthly-revenue',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取经营数据概览
   * GET /merchant/statistics/business-overview
   */
  getBusinessOverview: (params?: {
    period?: string;                // 统计周期 'today' | 'week' | 'month' | 'year'
  }) => {
    return request({
      url: '/merchant/statistics/business-overview',
      method: 'GET',
      data: params
    })
  }
}

// 导出所有API模块
export {
  ProfileAPI,
  WalletAPI,
  BankCardAPI,
  SettingsAPI,
  SupportAPI,
  CacheAPI,
  SecurityAPI,
  SystemAPI,
  StatisticsAPI
}

// 默认导出（兼容现有代码）
export default {
  Profile: ProfileAPI,
  Wallet: WalletAPI,
  BankCard: BankCardAPI,
  Settings: SettingsAPI,
  Support: SupportAPI,
  Cache: CacheAPI,
  Security: SecurityAPI,
  System: SystemAPI,
  Statistics: StatisticsAPI
}
